#include "comm.hpp"

Init init;
int main()
{
    // 1.获取唯一标识同一共享内存的key值
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("get key success", Debug) << "[" << TransKeyToHex(k) << "]" << endl;

    // 2.创建一个全新的共享内存
    int shmid = shmget(k, SHMSIZE, IPC_CREAT | IPC_EXCL | 0666);
    // 通过k值申请SHMSIZE大小的共享内存，如果成功返回，就是一个全新的shm，且权限是0666
    Log("get shm success", Debug) << "[" << shmid << "]" << endl;
    // sleep(10);

    // 3.挂接共享内存到地址空间上（建立映射）
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    assert(shmaddr != nullptr);
    Log("attach shm success", Debug) << endl;

    // 使用共享内存
    int fd = openFIFO(READ);

    while (true)
    {
        Wait(fd);
        printf("%s\n", shmaddr);
        if (strcmp(shmaddr, "quit") == 0)
            break;
        // sleep(1);//每隔一秒读取一次，即使没有数据刷新，也会重复读
    }
    printf("quit\n");

    // 4.去关联共享内存
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("dettach shm success", Debug) << endl;

    // 5.删除共享内存
    int ret = shmctl(shmid, IPC_RMID, NULL); // IPC_RMID:即使当前有进程挂接这块共享内存，也直接删除
    assert(ret != -1);
    Log("delete shm success", Debug) << "[" << shmid << "][" << TransKeyToHex(k) << "]" << endl;

    closeFIFO(fd);

    return 0;
}
